package com.me.controllers;

import com.me.annotation.Inject;
import com.me.dao.DbContext;
import com.me.dao.db.DbSet;
import com.me.model.User;
import com.me.model.viewmodel.UserViewModel;
import com.me.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserController extends Controller {
	@Inject private DbContext db;
	@Inject private UserService userv;


	@Inject
	public UserController(HttpServletRequest req, HttpServletResponse resp) {
		super(req, resp);
	}

	@Override
	public String index(String arg) {
		return mycenter(arg);
	}

	public String mycenter(String arg) {
		return view("mycenter",  new UserViewModel(getSessionUser()));
	}

	public String updateInfo() {
		UserViewModel model = (UserViewModel) Model;
		User u = getSessionUser();
		u.setId(model.getId());
		u.setName(model.getName());
		u.setPhone(model.getPhone());
		u.setAddress(model.getAddress());
		if (userv.update(u)) {
			setRedirectParam("msg","更改信息成功");
			return redirectToAction("mycenter");
		}

		setRedirectParam("msg","更改信息失败");
		return redirectToAction("mycenter");
	}

	public String updatePwd() {
		UserViewModel model = (UserViewModel) Model;
		User u = getSessionUser();
		if (model.getPassword().equals(u.getPassword())) {
			setRedirectParam("msg","更新密码成功");
			return redirectToAction("mycenter");
		}
		setRedirectParam("msg","原密码错误");
		return redirectToAction("mycenter");
	}

	public String logout(String arg) {
		clearSessionUser();
		return redirectToAction("login");
	}

	public String login(String arg) {
		return view(new UserViewModel());
	}

	public String register(String arg) {
		return view(new UserViewModel());
	}

	public String login() {
		UserViewModel model = (UserViewModel) Model;
		User u = userv.login(model.getUsername(), model.getPassword());
		if (u != null) {
			setSessionAttr("user", u);

			return redirectToAction("onLogin","order","");
		}
		setRedirectParam("error", "用户名或密码错误");
		return redirectToAction("login");
	}

	public String register() {
		UserViewModel u = (UserViewModel) Model;
		if (userv.register(new User(u), false)) {
			u.setPassword("");
			setModel(u);
			setRedirectParam("error", "注册成功，请登录");
			return redirectToAction("login");
		}

		u.setPassword("");
		setRedirectParam("error", "用户名重复");
		return redirectToAction("register", u);
	}


}
